<template>
  <div id="asyncRoutesConfig">

    <template v-if="isSelect">
      <el-tree
        :data="data"
        node-key="id"
        default-expand-all
        @node-drag-enter="handleDragEnter"
        @node-drop="handleDrop"
        draggable
        :expand-on-click-node="false"
        :allow-drop="allowDrop"
        :allow-drag="allowDrag">

        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <template v-if="data.id == 0">
              <el-button type="primary" @click="append(data)" style="width:110px">
                <i class="iconfont icon-tianjia"></i>
              </el-button>
            </template>
            <template v-else>
              <el-button type="primary" @click="append(data)" >
                <i class="iconfont icon-tianjia"></i>
              </el-button>
              <el-button type="warning" @click="edit(data)">
                <i class="iconfont icon-bianji"></i>
              </el-button>
              <el-button type="danger" @click="remove(data)">
                <i class="iconfont icon-shanchu"></i>
              </el-button>
            </template>
          </span>
        </span>
      </el-tree>
    </template>

    <template v-else>
      <router-view />
    </template>
  </div>
</template>

<script>
import {
  getMenuTree,deleteMenuById,moveMenu
} from '@/assets/request/api.js';
export default {
  name: 'asyncRoutesConfig',
  data() {
    return {

      data: [{
        id: 0,
        label: '异步路由管理',
        children: []
      }],
      isSelect: true
    }
  },
  methods: {
    append(data) {
      this.isSelect = false
      this.$router.push({'name':"asyncRoutesConfigAddRoutes",'params': data })
    },
    edit(data) {
      this.isSelect = false
      this.$router.push({'name':"asyncRoutesConfigEditRoutes",'params': data })
    },
    remove(data) {
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMenuById(data.id).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.initData()
        }).catch(err => {
          this.$message({
            type: 'error',
            message: err.message
          });   
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    handleDragEnter(draggingNode, dropNode, ev) {
      console.log('tree drag enter: ', dropNode.label);
    },
    /**
     * 移动结束
     * @param {*} draggingNode 拖拽结点
     * @param {*} dropNode 移动到某个结点
     * @param {*} type  dropType inner 在某结点里面  before 在某结点之前 after 在某结点之后 前中后
     */
    handleDrop(draggingNode, dropNode, dropType, ev) {
      
      // 触发接口更新
      console.log('tree drop: ', draggingNode ,dropNode, dropType);

      let moveMenuData = {
        currentId: draggingNode.data.id,
        dropId: dropNode.data.id,
        mode: dropType,
      }

      moveMenu(moveMenuData).then(res => {
        console.log(res)
        this.$message({
          message: '移动成功',
          type: 'success'
        });
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err.message
        });  
      })



    },
    /**
     * 是否可放置 
     * @param {*} draggingNode 拖拽结点
     * @param {*} dropNode 移动到某个结点
     * @param {*} type  前中后
     */
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.data.parentId === 0 && dropNode.data.parentId !== 0 && (type !== 'before' ||  type !== 'after')) {
        console.log('一级菜单节点不允许降为二、三级节点')
        return false
      } else if (draggingNode.data.parentId !== 0 && dropNode.data.parentId === 0 && type !== 'inner') {   // 这个是正确的
        console.log('非一级节点不允许拖拽成为一级节点')
        return false
      } else if (dropNode.data.id === 0) {
        console.log('禁止与超级菜单进行拖拽')
        return false
      } else {
        return true
      }
    },
    // 是否可拖拽
    allowDrag(draggingNode) {
      return true
    },
    // 每变更一次，重新获取树形结构
    async initData() {
      await getMenuTree().then(res => {
        this.data[0].children = res.data
      }).catch(err => {
        this.$message({
          message: '菜单列表获取出错',
          type: 'error'
        });
      })
    }
  },
  mounted() {
    // 解决如果在新增用户、更新用户界面 刷新页面，导致页面渲染出错
    if(!this.$router.history.current.meta.isSelect) {
      this.$router.push({name:'asyncRoutesConfig'})
    }
  },
  created() {
    this.initData()
  },
  watch: {
    $route(to,from) {
      if(to.path === '/authority/asyncRoutesConfig') { 
        this.isSelect = true
        this.initData()
      }
    }
  },
    
}
</script>

<style scoped lang="scss">


.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .ivu-btn {
    margin-left: 8px;
    font-size: 24px;
  }

  .el-button {
    line-height: 0px;
    height: 24px;
    padding: 6px;
  }
}

 
</style>
